{% extends "base.html" %}

{% block title %}系统管理 - xbot管理后台{% endblock %}

{% block page_title %}系统管理{% endblock %}

{% block extra_css %}
<style>
    .dashboard-stat-icon {
        height: 60px;
        width: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 12px;
        font-size: 1.5rem;
        color: white;
        margin-bottom: 0.5rem;
    }

    .status-dot {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        margin-right: 8px;
        background-color: #ccc;
    }

    .status-dot.online {
        background-color: #28a745;
    }

    .status-dot.offline {
        background-color: #dc3545;
    }

    .status-dot.waiting {
        background-color: #ffc107;
    }

    .stat-card {
        position: relative;
        overflow: hidden;
        margin-bottom: 1.5rem;
        border-radius: 10px;
        overflow: hidden;
        transition: all 0.3s;
    }

    .stat-card::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 70%);
        opacity: 0;
        transform: scale(0.5);
        transition: transform 0.5s ease, opacity 0.5s ease;
    }

    .stat-card:hover::before {
        opacity: 1;
        transform: scale(1);
    }

    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
    }

    .metric-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 1.5rem;
    }

    .system-info-table td {
        padding: 8px;
        vertical-align: middle;
    }

    .system-info-table td:first-child {
        font-weight: 500;
        width: 40%;
    }

    .log-viewer {
        background-color: #1e1e1e;
        color: #f0f0f0;
        border-radius: 8px;
        padding: 1rem;
        font-family: 'Courier New', monospace;
        height: 400px;
        overflow-y: auto;
        margin-bottom: 1rem;
        display: block !important;
        z-index: 1;
    }

    .log-line {
        margin: 0;
        padding: 2px 0;
        white-space: pre-wrap;
        word-break: break-all;
        display: block !important;
    }

    .log-line.info {
        color: #58B2DC;
    }

    .log-line.debug {
        color: #B0C4DE;
    }

    .log-line.warning {
        color: #FFD700;
    }

    .log-line.error {
        color: #FF6A6A;
    }

    .log-line.critical {
        color: #FF2400;
        font-weight: bold;
    }

    .log-controls {
        margin-bottom: 1rem;
    }

    .progress {
        height: 10px;
        border-radius: 5px;
        margin-bottom: 1rem;
    }

    .progress-bar {
        transition: width 0.3s ease-in-out;
    }

    .progress-bar[data-value]::before {
        content: attr(data-value) '%';
        position: absolute;
        right: 5px;
        color: rgba(255, 255, 255, 0.8);
        font-size: 0.75rem;
    }

    .card.dashboard-card {
        margin-bottom: 2rem;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        border-radius: 8px;
    }

    .row {
        margin-bottom: 1.5rem;
    }

    .col-12, .col-lg-6 {
        margin-bottom: 1.5rem;
    }

    #terminal-container.fullscreen {
        position: fixed;
        top: 75px;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 9999;
        height: calc(100vh - 75px) !important;
    }

    /* 终端iframe样式 */
    #terminal-iframe {
        width: 100%;
        height: 100%;
        border: none;
        background-color: #000;
    }

    /* 确保终端错误提示可见 */
    .terminal-error {
        color: #ff6b6b;
        text-align: center;
        padding: 20px;
    }

    /* 避免iframe内容溢出 */
    #terminal-container {
        overflow: hidden;
    }

    /* 调整日志容器可见性 */
    .logs-container {
        display: block !important;
        visibility: visible !important;
    }

    /* 简化日志查看器样式 */
    #simple-log-viewer {
        background-color: #1e1e1e;
        color: #f0f0f0;
        border-radius: 8px;
        padding: 1rem;
        font-family: 'Courier New', monospace;
        height: 400px;
        overflow-y: auto;
        white-space: pre-wrap;
        word-break: break-all;
    }
</style>
{% endblock %}

{% block page_actions %}
{% endblock %}

{% block content %}
<div class="container-fluid p-0">
    <!-- 系统概览 -->
    <div class="row">
        <div class="col-12">
            <div class="card dashboard-card mb-4" data-aos="fade-up">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="bi bi-speedometer2 me-2 text-primary"></i>系统概览
                    </h5>
                    <span id="last-updated" class="text-muted small">最后更新: {{ system_status.time }}</span>
                </div>
                <div class="card-body px-0 py-3">
                    <div class="metric-grid px-4">
                        <!-- 运行时间 -->
                        <div class="stat-card" data-aos="fade-up" data-aos-delay="100">
                            <div class="dashboard-stat-icon" style="background: linear-gradient(135deg, #E74C3C, #C0392B);">
                                <i class="bi bi-clock-history"></i>
                            </div>
                            <h6 class="stat-title">运行时间</h6>
                            <div class="stat-value" id="uptime-value">{{ system_status.uptime|default('获取中...') }}</div>
                            <div class="stat-description" id="start-time">启动于 {{ system_status.start_time|default('--') }}</div>
                        </div>

                        <!-- 内存占用 -->
                        <div class="stat-card" data-aos="fade-up" data-aos-delay="200">
                            <div class="dashboard-stat-icon" style="background: linear-gradient(135deg, #9B59B6, #8E44AD);">
                                <i class="bi bi-memory"></i>
                            </div>
                            <h6 class="stat-title">内存占用</h6>
                            <div class="stat-value" id="memory-value">{{ (system_status.memory_used / (1024*1024*1024))|round(2) }}GB / {{ (system_status.memory_total / (1024*1024*1024))|round(2) }}GB</div>
                            <div class="stat-description">
                                <div class="progress">
                                    <div class="progress-bar bg-purple memory-progress" role="progressbar" data-value="{{ system_status.memory_percent }}" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                            </div>
                        </div>

                        <!-- CPU 使用率 -->
                        <div class="stat-card" data-aos="fade-up" data-aos-delay="300">
                            <div class="dashboard-stat-icon" style="background: linear-gradient(135deg, #F39C12, #D35400);">
                                <i class="bi bi-cpu"></i>
                            </div>
                            <h6 class="stat-title">CPU 使用率</h6>
                            <div class="stat-value" id="cpu-value">{{ system_status.cpu_percent|default('0') }}%</div>
                            <div class="stat-description">
                                <div class="progress">
                                    <div class="progress-bar bg-warning cpu-progress" role="progressbar" data-value="{{ system_status.cpu_percent }}" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                            </div>
                        </div>

                        <!-- 磁盘使用 -->
                        <div class="stat-card" data-aos="fade-up" data-aos-delay="400">
                            <div class="dashboard-stat-icon" style="background: linear-gradient(135deg, #2ECC71, #27AE60);">
                                <i class="bi bi-hdd"></i>
                            </div>
                            <h6 class="stat-title">磁盘使用</h6>
                            <div class="stat-value" id="disk-value">{{ system_status.disk_percent|default('0') }}%</div>
                            <div class="stat-description">
                                <div class="progress">
                                    <div class="progress-bar bg-success disk-progress" role="progressbar" data-value="{{ system_status.disk_percent }}" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 系统详细信息 -->
    <div class="row">
        <!-- 系统信息卡片 -->
        <div class="col-lg-6">
            <div class="card dashboard-card mb-4" data-aos="fade-up">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="bi bi-info-circle me-2 text-primary"></i>系统信息
                    </h5>
                    <button class="btn btn-sm btn-outline-primary" id="btn-refresh-system">
                        <i class="bi bi-arrow-clockwise"></i>
                    </button>
                </div>
                <div class="card-body">
                    <table class="table table-hover system-info-table">
                        <tbody>
                            <tr>
                                <td>主机名</td>
                                <td id="hostname">加载中...</td>
                            </tr>
                            <tr>
                                <td>操作系统</td>
                                <td id="platform">加载中...</td>
                            </tr>
                            <tr>
                                <td>Python版本</td>
                                <td id="python_version">加载中...</td>
                            </tr>
                            <tr>
                                <td>CPU核心数</td>
                                <td id="cpu_count">加载中...</td>
                            </tr>
                            <tr>
                                <td>总内存</td>
                                <td id="memory_total">加载中...</td>
                            </tr>
                            <tr>
                                <td>可用内存</td>
                                <td id="memory_available">加载中...</td>
                            </tr>
                            <tr>
                                <td>总磁盘空间</td>
                                <td id="disk_total">加载中...</td>
                            </tr>
                            <tr>
                                <td>可用磁盘空间</td>
                                <td id="disk_free">加载中...</td>
                            </tr>
                            <tr>
                                <td>更新时间</td>
                                <td id="update_time">加载中...</td>
                            </tr>
                        </tbody>
                    </table>
                    <div id="error_message" class="alert alert-warning" style="display: none;"></div>
                </div>
            </div>
        </div>

        <!-- 机器人信息卡片 -->
        <div class="col-lg-6">
            <div class="card dashboard-card mb-4" data-aos="fade-up">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="bi bi-shield-check me-2 text-primary"></i>机器人信息
                    </h5>
                </div>
                <div class="card-body">
                    <div class="bot-info-container">
                        <div class="d-flex align-items-center mb-3">
                            <div class="status-dot" id="status-dot"></div>
                            <span id="status-text" class="me-2">获取中...</span>
                            <span class="badge bg-secondary" id="status-detail">-</span>
                        </div>

                        <table class="table table-hover system-info-table">
                            <tbody>
                                <tr>
                                    <td>微信昵称</td>
                                    <td id="bot-nickname">-</td>
                                </tr>
                                <tr>
                                    <td>微信ID</td>
                                    <td id="bot-wxid">-</td>
                                </tr>
                                <tr>
                                    <td>微信号</td>
                                    <td id="bot-alias">-</td>
                                </tr>
                                <tr>
                                    <td>登录设备</td>
                                    <td id="bot-device">-</td>
                                </tr>
                                <tr>
                                    <td>登录时间</td>
                                    <td id="login-time">-</td>
                                </tr>
                            </tbody>
                        </table>

                        <div class="text-center mt-3">
                            <div class="d-flex flex-wrap justify-content-center gap-2">
                                <button class="btn btn-sm btn-primary" id="btn-switch-account">
                                    <i class="bi bi-person-switch me-1"></i>切换账号
                                </button>
                                <button class="btn btn-sm btn-outline-secondary" id="btn-show-qrcode">
                                    <i class="bi bi-qr-code me-1"></i>显示二维码
                                </button>
                                <button class="btn btn-sm btn-danger" id="btn-restart-docker">
                                    <i class="bi bi-arrow-repeat me-1"></i>重启容器
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 系统日志部分 -->
    <div class="row" id="logs-section">
        <div class="col-12">
            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="bi bi-journal-text me-2 text-primary"></i>系统日志
                    </h5>
                    <button class="btn btn-sm btn-outline-primary" id="btn-simple-refresh-logs">
                        <i class="bi bi-arrow-clockwise"></i> 刷新日志
                    </button>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <div class="d-flex gap-2 mb-2">
                            <select class="form-select form-select-sm" id="simple-log-level" style="max-width: 150px;">
                                <option value="all">所有级别</option>
                                <option value="debug">Debug及以上</option>
                                <option value="info">Info及以上</option>
                                <option value="warning">Warning及以上</option>
                                <option value="error">Error及以上</option>
                            </select>
                            <button class="btn btn-sm btn-outline-secondary" id="btn-simple-copy-logs">
                                <i class="bi bi-clipboard"></i> 复制
                            </button>
                            <a href="/api/system/logs/download" class="btn btn-sm btn-outline-secondary" download>
                                <i class="bi bi-download"></i> 下载
                            </a>
                        </div>
                    </div>
                    
                    <!-- 日志查看器 -->
                    <pre id="simple-log-viewer">正在加载日志...</pre>
                </div>
            </div>
        </div>
    </div>

    <!-- 终端区域 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">终端服务</h5>
                    <div>
                        <a href="/terminal" class="btn btn-sm btn-primary me-2">打开终端页面</a>
                        <a href="http://localhost:3000" target="_blank" class="btn btn-sm btn-outline-primary">直接访问终端</a>
                    </div>
                </div>
                <div class="card-body">
                    <div class="alert alert-info">
                        <h6 class="alert-heading">终端服务状态检查与操作指南</h6>
                        <hr>
                        <ol>
                            <li><strong>终端服务状态检查</strong>：在系统命令行中运行 <code>ps aux | grep wetty</code> 查看WeTTy服务是否运行</li>
                            <li><strong>访问方式</strong>：
                                <ul>
                                    <li>方式一：点击上方的<strong>打开终端页面</strong>按钮，在管理后台中使用</li>
                                    <li>方式二：点击上方的<strong>直接访问终端</strong>按钮，直接打开WeTTy服务</li>
                                </ul>
                            </li>
                            <li><strong>如果终端不可访问</strong>，请尝试重启WeTTy服务：
                                <div class="bg-dark text-light p-2 mt-1 rounded">
                                    <code>pkill -f wetty && wetty --port 3000 --host 0.0.0.0 --allow-iframe --base / --command /bin/bash &</code>
                                </div>
                            </li>
                            <li>如果重启后仍然无法访问，请检查端口3000是否已被占用：<code>netstat -tuln | grep 3000</code></li>
                        </ol>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <span class="text-muted">WeTTy终端服务端口：</span>
                            <span class="fw-bold">3000</span>
                        </div>
                        <div>
                            <button id="check-terminal" class="btn btn-sm btn-outline-primary me-2">检查终端服务状态</button>
                            <button id="restart-terminal" class="btn btn-sm btn-outline-warning">重启终端服务</button>
                        </div>
                    </div>
                    <div id="terminal-status" class="mt-3 d-none">
                        <div class="d-flex align-items-center">
                            <div class="spinner-border spinner-border-sm text-primary me-2" role="status">
                                <span class="visually-hidden">正在检查...</span>
                            </div>
                            <span>正在检查终端服务状态...</span>
                        </div>
                    </div>
                    <div id="terminal-log" class="mt-3 d-none">
                        <h6 class="text-muted">终端服务诊断日志：</h6>
                        <div class="border rounded bg-light p-2" style="max-height: 200px; overflow-y: auto; font-family: monospace; font-size: 12px; white-space: pre-wrap;"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取系统日志函数
        function getSimpleLogs() {
            const logViewer = document.getElementById('simple-log-viewer');
            
            if (!logViewer) {
                console.error('找不到日志查看器元素!');
                return;
            }
            
            logViewer.textContent = '正在加载日志...';
            
            const logLevel = document.getElementById('simple-log-level')?.value || 'all';
            const queryString = logLevel !== 'all' ? `?log_level=${logLevel}` : '';
            
            console.log(`请求日志: /api/system/logs${queryString}`);
            
            fetch(`/api/system/logs${queryString}`)
                .then(response => {
                    console.log('日志API响应状态:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('收到日志数据, 条数:', data.logs?.length || 0);
                    
                    if (!data.success) {
                        logViewer.textContent = `获取日志失败: ${data.error || '未知错误'}`;
                        return;
                    }
                    
                    if (!data.logs || data.logs.length === 0) {
                        logViewer.textContent = '没有找到日志内容';
                        return;
                    }
                    
                    let logContent = '';
                    data.logs.forEach(log => {
                        let line = '';
                        if (log.timestamp) {
                            line += `${log.timestamp} | `;
                        }
                        if (log.level) {
                            line += `${log.level.toUpperCase()} | `;
                        }
                        line += log.message || log.raw || '';
                        logContent += line + '\n';
                    });
                    
                    logViewer.textContent = logContent;
                    logViewer.scrollTop = logViewer.scrollHeight;
                })
                .catch(error => {
                    console.error('获取日志出错:', error);
                    logViewer.textContent = `获取日志出错: ${error.message}`;
                });
        }
        
        // 安全地添加事件监听器
        function safeAddEventListener(id, event, callback) {
            const element = document.getElementById(id);
            if (element) {
                element.addEventListener(event, callback);
                return true;
            } else {
                console.warn(`无法添加事件监听器: 找不到元素 ${id}`);
                return false;
            }
        }
        
        // 获取初始日志
        getSimpleLogs();
        
        // 添加事件监听器
        safeAddEventListener('btn-simple-refresh-logs', 'click', function() {
            console.log('手动刷新日志');
            getSimpleLogs();
        });
        
        safeAddEventListener('simple-log-level', 'change', function() {
            console.log('日志级别已更改:', this.value);
            getSimpleLogs();
        });
        
        safeAddEventListener('btn-simple-copy-logs', 'click', function() {
            const logContent = document.getElementById('simple-log-viewer')?.textContent || '';
            navigator.clipboard.writeText(logContent)
                .then(() => alert('日志已复制到剪贴板'))
                .catch(err => console.error('复制失败:', err));
        });
        
        // 每30秒刷新一次日志
        setInterval(getSimpleLogs, 30000);
        
        // 系统信息获取函数
        function getSystemInfo() {
            console.log('获取系统信息...');
            
            fetch('/api/system/info')
                .then(response => response.json())
                .then(data => {
                    console.log('收到系统信息:', data);
                    
                    if (!data.success) {
                        document.getElementById('error_message').textContent = `获取系统信息失败: ${data.error || '未知错误'}`;
                        document.getElementById('error_message').style.display = 'block';
                        return;
                    }
                    
                    // 更新系统信息表格
                    const info = data.data || {};
                    
                    // 更新表格数据
                    document.getElementById('hostname').textContent = info.hostname || '未知';
                    document.getElementById('platform').textContent = info.os || info.platform || '未知';
                    document.getElementById('python_version').textContent = info.python || info.python_version || '未知';
                    document.getElementById('cpu_count').textContent = info.cpu_count || '未知';
                    
                    // 隐藏错误信息（如果有）
                    document.getElementById('error_message').style.display = 'none';
                })
                .catch(error => {
                    console.error('获取系统信息出错:', error);
                    document.getElementById('error_message').textContent = `获取系统信息出错: ${error.message}`;
                    document.getElementById('error_message').style.display = 'block';
                });
        }
        
        // 获取机器人信息
        function getBotInfo() {
            console.log('获取机器人信息...');
            
            fetch('/api/bot/status')
                .then(response => response.json())
                .then(data => {
                    console.log('收到机器人信息:', data);
                    
                    if (!data.success) {
                        console.error('获取机器人信息失败:', data.error || '未知错误');
                        return;
                    }
                    
                    const botInfo = data.data || {};
                    
                    // 更新状态指示器
                    const statusDot = document.getElementById('status-dot');
                    const statusText = document.getElementById('status-text');
                    const statusDetail = document.getElementById('status-detail');
                    
                    if (statusDot && statusText && statusDetail) {
                        if (botInfo.status === 'online' || botInfo.status === 'ready') {
                            statusDot.className = 'status-dot online';
                            statusText.textContent = '在线';
                            statusDetail.textContent = '正常运行中';
                            statusDetail.className = 'badge bg-success';
                        } else if (botInfo.status === 'waiting_login') {
                            statusDot.className = 'status-dot waiting';
                            statusText.textContent = '等待登录';
                            statusDetail.textContent = '等待扫码';
                            statusDetail.className = 'badge bg-warning';
                        } else {
                            statusDot.className = 'status-dot offline';
                            statusText.textContent = '离线';
                            statusDetail.textContent = botInfo.status || '未运行';
                            statusDetail.className = 'badge bg-danger';
                        }
                    }
                    
                    // 更新机器人信息
                    document.getElementById('bot-nickname').textContent = botInfo.nickname || '-';
                    document.getElementById('bot-wxid').textContent = botInfo.wxid || '-';
                    document.getElementById('bot-alias').textContent = botInfo.alias || '-';
                    document.getElementById('bot-device').textContent = botInfo.device_name || '-';
                    
                    // 格式化登录时间
                    if (botInfo.login_time) {
                        let loginTime = botInfo.login_time;
                        // 如果是时间戳，转换为日期
                        if (typeof loginTime === 'number') {
                            loginTime = new Date(loginTime * 1000).toLocaleString();
                        }
                        document.getElementById('login-time').textContent = loginTime;
                    } else {
                        document.getElementById('login-time').textContent = '-';
                    }
                })
                .catch(error => {
                    console.error('获取机器人信息出错:', error);
                });
        }
        
        // 获取系统状态
        function getSystemStatus() {
            console.log('获取系统状态...');
            
            fetch('/api/system/status')
                .then(response => response.json())
                .then(data => {
                    console.log('收到系统状态:', data);
                    
                    if (!data.success) {
                        console.error('获取系统状态失败:', data.error || '未知错误');
                        return;
                    }
                    
                    const status = data.data || {};
                    
                    // 更新内存信息
                    if (status.memory_total) {
                        const totalGB = (status.memory_total / (1024*1024*1024)).toFixed(2);
                        document.getElementById('memory_total').textContent = `${totalGB} GB`;
                    }
                    
                    if (status.memory_used && status.memory_total) {
                        const availableGB = ((status.memory_total - status.memory_used) / (1024*1024*1024)).toFixed(2);
                        document.getElementById('memory_available').textContent = `${availableGB} GB`;
                    }
                    
                    // 更新磁盘信息
                    if (status.disk_total) {
                        const totalGB = (status.disk_total / (1024*1024*1024)).toFixed(2);
                        document.getElementById('disk_total').textContent = `${totalGB} GB`;
                    }
                    
                    if (status.disk_used && status.disk_total) {
                        const freeGB = ((status.disk_total - status.disk_used) / (1024*1024*1024)).toFixed(2);
                        document.getElementById('disk_free').textContent = `${freeGB} GB`;
                    }
                    
                    // 更新时间信息
                    document.getElementById('update_time').textContent = new Date().toLocaleString();
                    
                    // 更新概览信息
                    if (status.uptime) {
                        document.getElementById('uptime-value').textContent = status.uptime;
                    }
                    
                    if (status.start_time) {
                        document.getElementById('start-time').textContent = `启动于 ${status.start_time}`;
                    }
                    
                    // 更新CPU使用率
                    if (status.cpu_percent !== undefined) {
                        document.getElementById('cpu-value').textContent = `${status.cpu_percent}%`;
                        const cpuProgressBar = document.querySelector('.cpu-progress');
                        if (cpuProgressBar) {
                            cpuProgressBar.style.width = `${status.cpu_percent}%`;
                            cpuProgressBar.setAttribute('data-value', status.cpu_percent);
                        }
                    }
                    
                    // 更新内存使用率
                    if (status.memory_percent !== undefined && status.memory_used && status.memory_total) {
                        const usedGB = (status.memory_used / (1024*1024*1024)).toFixed(2);
                        const totalGB = (status.memory_total / (1024*1024*1024)).toFixed(2);
                        document.getElementById('memory-value').textContent = `${usedGB}GB / ${totalGB}GB`;
                        
                        const memProgressBar = document.querySelector('.memory-progress');
                        if (memProgressBar) {
                            memProgressBar.style.width = `${status.memory_percent}%`;
                            memProgressBar.setAttribute('data-value', status.memory_percent);
                        }
                    }
                    
                    // 更新磁盘使用率
                    if (status.disk_percent !== undefined) {
                        document.getElementById('disk-value').textContent = `${status.disk_percent}%`;
                        const diskProgressBar = document.querySelector('.disk-progress');
                        if (diskProgressBar) {
                            diskProgressBar.style.width = `${status.disk_percent}%`;
                            diskProgressBar.setAttribute('data-value', status.disk_percent);
                        }
                    }
                    
                    // 更新最后更新时间
                    document.getElementById('last-updated').textContent = `最后更新: ${new Date().toLocaleString()}`;
                })
                .catch(error => {
                    console.error('获取系统状态出错:', error);
                });
        }
        
        // 初始化页面
        function initPage() {
            // 获取各种数据
            getSystemInfo();
            getBotInfo();
            getSystemStatus();
            
            // 添加按钮事件监听器
            safeAddEventListener('btn-refresh-system', 'click', function() {
                console.log('手动刷新系统信息');
                getSystemInfo();
                getSystemStatus();
            });
            
            safeAddEventListener('btn-switch-account', 'click', function() {
                console.log('切换账号');
                if (confirm('确定要切换微信账号吗？这将登出当前账号。')) {
                    fetch('/api/switch_account', { method: 'POST' })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                alert('已开始切换账号流程，请留意二维码');
                                setTimeout(getBotInfo, 3000);
                            } else {
                                alert(`切换失败: ${data.error || '未知错误'}`);
                            }
                        })
                        .catch(error => {
                            console.error('切换账号出错:', error);
                            alert(`切换账号出错: ${error.message}`);
                        });
                }
            });
            
            safeAddEventListener('btn-show-qrcode', 'click', function() {
                window.location.href = '/qrcode';
            });
            
            safeAddEventListener('btn-restart-docker', 'click', function() {
                if (confirm('确定要重启机器人容器吗？这将导致机器人短暂离线。')) {
                    fetch('/api/system/restart', { method: 'POST' })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                alert('已发送重启命令，容器正在重启中');
                            } else {
                                alert(`重启失败: ${data.error || '未知错误'}`);
                            }
                        })
                        .catch(error => {
                            console.error('重启容器出错:', error);
                            alert(`重启容器出错: ${error.message}`);
                        });
                }
            });
            
            // 处理终端相关按钮
            safeAddEventListener('check-terminal', 'click', function() {
                const statusElement = document.getElementById('terminal-status');
                const logElement = document.getElementById('terminal-log');
                
                statusElement.classList.remove('d-none');
                
                fetch('/api/terminal/diagnose')
                    .then(response => response.json())
                    .then(data => {
                        statusElement.classList.add('d-none');
                        logElement.classList.remove('d-none');
                        
                        const logContent = logElement.querySelector('div');
                        if (logContent) {
                            if (data.success) {
                                logContent.innerHTML = `<div class="text-success mb-2"><i class="bi bi-check-circle"></i> 终端服务状态: ${data.status.running ? '运行中' : '未运行'}</div>`;
                                if (data.logs && data.logs.length > 0) {
                                    data.logs.forEach(log => {
                                        logContent.innerHTML += `<div class="small">${log.replace(/\n/g, '<br>')}</div>`;
                                    });
                                }
                            } else {
                                logContent.innerHTML = `<div class="text-danger"><i class="bi bi-exclamation-triangle"></i> 检查失败: ${data.error || '未知错误'}</div>`;
                            }
                        }
                    })
                    .catch(error => {
                        statusElement.classList.add('d-none');
                        logElement.classList.remove('d-none');
                        
                        const logContent = logElement.querySelector('div');
                        if (logContent) {
                            logContent.innerHTML = `<div class="text-danger"><i class="bi bi-exclamation-triangle"></i> 检查出错: ${error.message}</div>`;
                        }
                    });
            });
            
            safeAddEventListener('restart-terminal', 'click', function() {
                if (confirm('确定要重启终端服务吗？')) {
                    const statusElement = document.getElementById('terminal-status');
                    const logElement = document.getElementById('terminal-log');
                    
                    statusElement.classList.remove('d-none');
                    
                    fetch('/api/terminal/restart', { method: 'POST' })
                        .then(response => response.json())
                        .then(data => {
                            statusElement.classList.add('d-none');
                            logElement.classList.remove('d-none');
                            
                            const logContent = logElement.querySelector('div');
                            if (logContent) {
                                if (data.success) {
                                    logContent.innerHTML = `<div class="text-success mb-2"><i class="bi bi-check-circle"></i> 终端服务已重启</div>`;
                                    if (data.logs && data.logs.length > 0) {
                                        data.logs.forEach(log => {
                                            logContent.innerHTML += `<div class="small">${log.replace(/\n/g, '<br>')}</div>`;
                                        });
                                    }
                                } else {
                                    logContent.innerHTML = `<div class="text-danger"><i class="bi bi-exclamation-triangle"></i> 重启失败: ${data.error || '未知错误'}</div>`;
                                }
                            }
                        })
                        .catch(error => {
                            statusElement.classList.add('d-none');
                            logElement.classList.remove('d-none');
                            
                            const logContent = logElement.querySelector('div');
                            if (logContent) {
                                logContent.innerHTML = `<div class="text-danger"><i class="bi bi-exclamation-triangle"></i> 重启出错: ${error.message}</div>`;
                            }
                        });
                }
            });
        }
        
        // 初始化页面
        initPage();
        
        // 定期刷新系统和机器人信息
        setInterval(getSystemInfo, 60000); // 每分钟刷新系统信息
        setInterval(getBotInfo, 30000);    // 每30秒刷新机器人信息
        setInterval(getSystemStatus, 30000); // 每30秒刷新系统状态
    });
</script>
{% endblock %}